# -*- coding: UTF-8 -*-
# -------------------------------------------------------------------------------
# Filename:     get-hostinfo-log2png.py
# UpdateDate:   2025/01/14
# Description:  一键导出memory&cpu测试日志【free -h && top -n 1 | grep '%Cpu'】中关键信息【Memory的used和CPU的idle】并生成图片。
# Example:      python get-hostinfo-log2png.py ./hostinfo.log ./test.png
# Depends:      如没安装matplotlib库，可以通过pip安装： pip install matplotlib
# Notes:        本脚本适用于Docker容器环境下运行；
#               [cam@cam~/]$free -h && top -n 1 | grep '%Cpu'
#                             total        used        free      shared  buff/cache   available
#               Mem:            31G        4.7G        465M         79M         26G         25G
#               Swap:          2.0G        1.5M        2.0G
#               %Cpu(s):  0.9 us,  0.4 sy,  0.0 ni, 98.3 id,  0.1 wa,  0.0 hi,  0.3 si,  0.0 st
# -------------------------------------------------------------------------------
import re
import sys
import matplotlib.pyplot as plt

#def plot_system_metrics(log_file_path, output_image_path):
def plot_system_metrics(log_file_path, output_image_path='default_system_metrics.png'):
    # 用于存储每个关键字对应数值的列表
    host_mem_values = []
    cpu_idle_values = []

    # 打开日志文件并读取每一行
    with open(log_file_path, 'r') as file:
        for line in file:
            # 提取Mem信息
            #mem_match = re.search(r'Mem:\s+\d+Gi\s+(\d+Gi)\s+\d+Gi\s+\d+Mi\s+\d+Gi\s+\d+Gi', line)
            mem_match = re.search(r'Mem:\s+\d+Gi\s+(\d+Gi)\s+', line)
            if mem_match:
                mem_value = int(mem_match.group(1).rstrip('Gi'))
                host_mem_values.append(mem_value)
            # 提取 CPU 空闲值
            cpu_match = re.search(r'%Cpu\(s\):\s+(\d+\.\d+)\s+us,+\s+(\d+\.\d+)\s+sy,+\s+(\d+\.\d+)\s+ni,+\s+(\d+\.\d+)\s+id,+\s', line)
            #pattern = r'%Cpu\(s\):\s+(\d+\.\d+)\s+us,+\s+(\d+\.\d+)\s+sy,+\s+(\d+\.\d+)\s+ni,+\s+(\d+\.\d+)\s+id,+\s'
            #cpu_match = re.search(pattern, line)
            if cpu_match:
                cpu_idle_value = float(cpu_match.group(4))
                cpu_idle_values.append(cpu_idle_value) 
    # 打印 host_mem_values 列表
    print("========host_mem_values 列表内容:")
    print(host_mem_values)
    print("========cpu_idle_values 列表内容:")
    print(cpu_idle_values)

    # 简单地使用索引作为x轴的值
    x = range(len(host_mem_values))

    # 绘制两条曲线图
    plt.figure(figsize=(10, 8))

    plt.subplot(2, 1, 1)
    plt.plot(x, host_mem_values, marker='o', label='Mem Info (Gi)')
    plt.title('Memory used Info')
    plt.xlabel('Index')
    plt.ylabel('Memory used (Gi)')
    plt.grid(True)

    plt.subplot(2, 1, 2)
    plt.plot(x, cpu_idle_values, marker='o', label='CPU Idle (%)')
    plt.title('CPU Idle Info')
    plt.xlabel('Index')
    plt.ylabel('CPU Idle (%)')
    plt.grid(True)

    # 调整布局以避免重叠
    plt.tight_layout()

    # 显示图例
    plt.legend()

    # 保存图形为PNG图片
    plt.savefig(output_image_path)

    # 注意：这里不调用plt.show()，因为我们只保存图片而不显示它

if __name__ == "__main__":
    # 检查命令行参数数量
    if len(sys.argv) < 2 or len(sys.argv) > 3:
        print("Usage: python script.py <log_file_path> [<output_image_path>]")
        print("If <output_image_path> is not provided, the default 'default_system_metrics.png' will be used.")
        sys.exit(1)

    # 获取命令行参数
    log_file_path = sys.argv[1]
    output_image_path = sys.argv[2] if len(sys.argv) == 3 else 'default_system_metrics.png'

    # 调用函数绘制并保存图形
    plot_system_metrics(log_file_path, output_image_path)

